package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"shuqi-novel/cache"
	"shuqi-novel/models"

	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		user = models.User{
			Account:   in.Account,
			Password:  in.Password,
			HeadImage: "https://c-ssl.dtstatic.com/uploads/blog/202203/22/20220322210603_2d84a.thumb.400_0.jpg",
			NickName:  fmt.Sprintf("用户_%d", rand.Intn(10000)),
		}
		models.DB.Debug().Create(&user)
	}

	if in.Password != user.Password {
		return nil, errors.New("账号密码错误,登录失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误,登录失败")
	}

	return &novelrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
